package com.skyworth.ui.api;

import android.content.Context;
import android.widget.TextView;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author : yellowlgx
 * @ClassName SkyTextClock
 * @Description : TODO
 * @date : 2017/7/19 19:50
 */
public class SkyTextClock extends TextView
{
    UpdateRunnable updateRunnable;
    private boolean mDestroy = false;
    private String mFormat24 = "HH:mm";

    public SkyTextClock(Context context)
    {
        super(context);
        delayGetTime();
    }

    public void setFormat24Hour(String format)
    {
        mFormat24 = format;
        getTime();
    }

    private void delayGetTime()
    {
        if(updateRunnable == null)
            updateRunnable = new UpdateRunnable(this);
        this.postDelayed(updateRunnable, 60000);
    }

    private void getTime()
    {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat f = new SimpleDateFormat(mFormat24);
        this.setText(f.format(date));
    }

    public void onDestroy()
    {
        mDestroy = true;
        removeCallbacks(updateRunnable);
        updateRunnable = null;
    }

    //使用static修复内存泄漏
    private static class UpdateRunnable implements Runnable
    {
        WeakReference<SkyTextClock> ref;
        private UpdateRunnable(SkyTextClock tc)
        {
            ref = new WeakReference<SkyTextClock>(tc);
        }

        @Override
        public void run()
        {
            if(ref == null)
                return ;
            SkyTextClock tc = ref.get();
            if(ref.get() == null)
                return ;
            if (!tc.mDestroy)
            {
                tc.getTime();
                tc.delayGetTime();
            }
        }
    }
}
